package com.smcaiot.filesync.starter.handler.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.smcaiot.filesync.starter.annotation.SmallPath;
import com.smcaiot.filesync.starter.constants.Constants;
import com.smcaiot.filesync.starter.constants.HandlerType;
import com.smcaiot.filesync.starter.entity.ReceiveParams;
import com.smcaiot.filesync.starter.handler.SyncFileHandler;
import com.smcaiot.filesync.starter.handler.SyncFinishHandler;
import com.smcaiot.filesync.starter.util.ReflectTool;
import com.smcaiot.filesync.starter.util.RestResp;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

@Slf4j
public abstract class AbstractPushFileHandler<T> extends BaseHandler<T> implements SyncFileHandler<T> {

    @Override
    public boolean syncFile(T entity) {
        String filePath = ReflectTool.getFieldValue(entity, SmallPath.class);
        if (StrUtil.isBlank(filePath)) {
            log.debug("推送文件时，找不到文件地址");
            return false;
        }
        String base64 = fileHandler.downloadBase64(filePath);
        ReceiveParams<T> params = new ReceiveParams<T>().setEntity(entity).setBase64(base64)
                .setFileName(getNameByPath(filePath))
                .setPathFieldName(ReflectTool.getFieldName(entity, SmallPath.class));
        params.setHandlerType(HandlerType.push).setEntityClassName(entity.getClass().getSimpleName());
        return receiveFile(params);
    }

    private boolean receiveFile(ReceiveParams<T> params) {
        try (HttpResponse response = HttpUtil.createPost(getReceiveUrl()).headerMap(getHeaderMap(), true)
                .body(JSONUtil.toJsonStr(params)).execute()) {
            String resultStr = response.body();
            RestResp restResp = JSONUtil.toBean(resultStr, RestResp.class);
            if (!RestResp.CODE_SUCCESS.equals(restResp.getCode()) || Objects.isNull(restResp.getData())) {
                log.warn("推送文件接口失败：{}", JSONUtil.toJsonStr(restResp));
                return false;
            }
            return true;
        }
    }

    private String getReceiveUrl() {
        return Objects.isNull(remoteInfo) || StrUtil.isBlank(remoteInfo.getUrl()) ?
                fileSyncProp.getPush().getRemoteHost() + Constants.URL_RECEIVE_FILE : remoteInfo.getUrl();
    }

}
